<template>
  <!-- 选择课题成果报告 -->
  <div>
    <a-button type="primary" icon="plus" @click="handleOpen()">添加成果</a-button>
    <DialogForm :customFooter="true" ref="dialogForm" headerTitle="选择活动成果" :visible.sync="visible" :width="1500">
      <template slot="formHeader">
        <!-- 搜索 -->
        <searchData ref="searchData" :searchData="searchArr" @search="search"></searchData>
        <div style="max-height: 300px; overflow: auto">
          <a-tag
            v-for="item in selectedRow"
            :key="item.id"
            class="mb10"
            :closable="true"
            color="#108ee9"
            @close="handleRemove(item.id)"
          >
            {{ item.register && item.register.topicName }}
          </a-tag>
        </div>
        <!-- 表格 -->
        <a-table
          :loading="loading"
          tableLayout="fixed"
          rowKey="id"
          size="default"
          :columns="columns"
          :dataSource="dataSource"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            type: 'checkbox',
            onSelectAll: onSelectAllChange,
            onSelect: onSelectChange
          }"
          :pagination="{
            current: pageNo,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSize: pageSize,
            showTotal: (total) => `共 ${total} 条数据`,
            total: total
          }"
          @change="handleTableChange"
        >
          <!-- 附件 -->
          <FileLink slot="files" slot-scope="text" :fileList="text" />
        </a-table>
      </template>
      <template slot="footer">
        <a-button
          type="primary"
          @click="
            $refs.searchData.form.resetFields()
            visible = false
          "
          class="button_right"
        >
          关闭
        </a-button>
        <a-button type="primary" :disabled="!selectedRowKeys || !selectedRowKeys.length" @click="handleConfirm">
          确认选择
        </a-button>
      </template>
    </DialogForm>
  </div>
</template>

<script>
import { qcActivityAchievement } from '@/api/quality/quality' // api
import DialogForm from '@/components/DialogForm' // 弹窗
import Selector from '@/components/Select/Selector' // 选择器
import SelectProject from '@/components/Select/SelectProject' // 项目名称

export default {
  name: 'ChooseQCActivityReport',
  components: {
    DialogForm
  },
  data() {
    return {
      loading: false, //表格加载
      visible: false, // 信息弹窗显隐控件
      selectedRowKeys: [], // 信息选中id集合
      selectedRow: [], // 信息选中对象集合
      queryParam: {}, // 查询参数
      dataSource: [], // 信息列表
      searchArr: [
        // 搜索框
        {
          name: '项目名称',
          type: SelectProject,
          needLink: false,
          isSelf: true,
          valueKey: 'projectId'
        },
        {
          name: '课题名称',
          type: 'input',
          value: 'topicName'
        },
        {
          name: '课题类型',
          type: Selector,
          selectType: '47',
          valueKey: 'topicTypeId'
        },
        {
          name: '活动开展年度',
          type: 'yearRange',
          value: 'year',
          attr: {
            rangeFormat: ['activeStartYear', 'activeEndYear'],
            placeholder: ['开始时间', '截止时间']
          }
        }
      ],
      columns: [
        {
          title: '项目名称',
          ellipsis: true,
          dataIndex: 'projectName'
        },
        {
          title: '课题注册号',
          align: 'center',
          width: 200,
          dataIndex: 'register.topicRegisterNumber'
        },
        {
          title: '课题名称',
          ellipsis: true,
          dataIndex: 'register.topicName'
        },
        {
          title: '课题类型',
          ellipsis: true,
          dataIndex: 'register.topicTypeName'
        },
        {
          dataIndex: 'files',
          title: '附件',
          scopedSlots: { customRender: 'files' }
        }
      ], // 表头
      pageSize: 10,
      pageNo: 1,
      total: 0
    }
  },
  props: {
    // 表单
    form: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    visible(e) {
      if (!e) {
        this.queryParam = {}
        this.pageSize = 10
        this.pageNo = 1
      }
    }
  },
  methods: {
    /**
     * 表格分页、排序、筛选变化时触发
     */
    handleTableChange(pagination){
      this.pageNo = pagination.current
      this.pageSize = pagination.pageSize
      this.loadData()
    },
    /**
     * 请求表格数据
     */
    loadData() {
      const requestParameters = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        query: { isQueryPast: true, ...this.queryParam }
      }
      this.loading = true
      qcActivityAchievement
        .getListByQuery(requestParameters)
        .then((res) => {
          this.loading = false
          res.data?.forEach((i) => {
            i.statusName = { PAST: '审批通过', REJECTED: '审批不通过', DRAFT: '待提交审批', SUBMITTED: '审批中' }[
              i.status
            ]
          })
          this.total = res.totalSize
          this.dataSource = res.data
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * @description: 移除选中
     * @param {*} id：业务id
     */
    handleRemove(id) {
      this.selectedRowKeys = this.selectedRowKeys.filter((i) => i !== id)
      this.selectedRow = this.selectedRow.filter((i) => i.id !== id)
    },
    /**
     * @description: 全选复选项改变
     * @param {*} selected：选中状态
     * @param {*} selectedRows：选中列表
     * @param {*} changeRows：改变项
     */
    onSelectAllChange(selected, selectedRows, changeRows) {
      const filter = (list) => {
        let map = new Map()
        for (let item of list) {
          if (!map.has(item.id)) {
            map.set(item.id, item)
          }
        }
        return [...map.values()]
      }
      if (selected) {
        this.selectedRowKeys = [...new Set(this.selectedRowKeys.concat(changeRows.map((i) => i.id)))]
        this.selectedRow = filter(this.selectedRow.concat(changeRows))
      } else {
        let changeRowKeys = changeRows.map((i) => i.id)
        this.selectedRowKeys = this.selectedRowKeys.filter((i) => !changeRowKeys.includes(i))
        this.selectedRow = this.selectedRow.filter((i) => !changeRowKeys.includes(i.id))
      }
    },
    /**
     * @description: 复选项改变
     * @param {*} record：选中项
     * @param {*} selected：选中状态
     * @param {*} selectedRows：选中列表
     */
    onSelectChange(record, selected) {
      if (selected) {
        this.selectedRowKeys.push(record.id)
        this.selectedRow.push(record)
      } else {
        this.selectedRowKeys = this.selectedRowKeys.filter((i) => i !== record.id)
        this.selectedRow = this.selectedRow.filter((i) => i.id !== record.id)
      }
    },
    /**
     * @description: 关联样板信息后回调
     */
    handleConfirm() {
      this.$set(this.form, 'achievementIds', this.selectedRowKeys)
      this.$set(this.form, 'achievements', this.selectedRow)
      // 重置搜索表单
      this.$refs.searchData?.form.resetFields()
      this.visible = false
    },
    // 搜索
    search(value) {
      value && (this.queryParam = value)
      this.loadData()
    },
    /**
     * @description: 打开选择弹窗
     */
    handleOpen() {
      if (this.form.achievements?.length) {
        this.selectedRowKeys = this.form.achievements.map((i) => i.id)
        this.selectedRow = this.$clone(this.form.achievements)
      }
      this.loadData()
      if (!this.visible) {
        this.visible = true
      }
    }
  }
}
</script>